package com.mypro.mydemo1.JDBC;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/TestExcelServlet")
public class TestExcelServlet extends HttpServlet {
    String message;
    @Override
    public void init() {
       message="初始化完成";
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out =resp.getWriter();
        out.print(message+"......<br>");
        try {

            XSSFWorkbook xssfWorkbook = new XSSFWorkbook(new FileInputStream("C:\\Users\\WangZhicheng\\Desktop\\授权码.xlsx"));

            int sheetNum = xssfWorkbook.getNumberOfSheets();
            System.out.println("该excel文件中总共有：" + sheetNum + "个sheet"+"<br>");

            for (int i = 0; i < sheetNum; i++) {

               out.println("读取第" + (i + 1) + "个sheet"+"<br>");
                XSSFSheet sheet = xssfWorkbook.getSheetAt(i);

                int maxRow = sheet.getLastRowNum();
                for (int row = 0; row <= maxRow; row++) {

                    if (sheet.getRow(row) != null) {
                        int maxRol = sheet.getRow(row).getLastCellNum();
                        out.println("--------第" + row + "行的数据如下--------");
                        for (int rol = 0; rol < maxRol; rol++) {
                            out.print(sheet.getRow(row).getCell(rol) + "  ");
                        }
                       out.print("<br>");
                    } else {
                        out.print("Row " + row + " does not exist in the sheet."+"<br>");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
